#include "stdafx.h"
#include "Utility.h"
#include "RenderProcess.h"
#include "MemTrack.h"

namespace bs
{
	RenderProcess::RenderProcess( ICanvas& canvas )
		: canvas(canvas)
	{
	}

	RenderProcess::~RenderProcess()
	{
		while(!this->renderInfos.empty())
		{
			SAFE_DELETE(this->renderInfos.back());
			this->renderInfos.pop_back();
		}
	}

	void RenderProcess::Run( int id, size_t time, size_t frames, size_t elapse, void* userData )
	{
		HDC backDc = this->canvas.PrepareToDraw();

		for(std::vector<RenderInfo*>::reverse_iterator itr=this->renderInfos.rbegin();
			itr!=this->renderInfos.rend(); ++itr)
		{
			(*itr)->renderer->Render(backDc);
		}

		this->canvas.FlushToScreen();
	}

	void RenderProcess::AddRenderer( IRenderable* renderer, int renderLayer )
	{
		RenderInfo* info = new RenderInfo(renderer, renderLayer);

		for(std::vector<RenderInfo*>::iterator itr=this->renderInfos.begin();
			itr!=this->renderInfos.end(); ++itr)
		{
			if(*info >= *(*itr))
			{
				this->renderInfos.insert(itr, info);
				return;
			}
		}

		this->renderInfos.push_back(info);
	}

	void RenderProcess::RemoveRenderer( IRenderable* renderer )
	{
		for(std::vector<RenderInfo*>::iterator itr=this->renderInfos.begin();
			itr!=this->renderInfos.end(); ++itr)
		{
			if((*itr)->renderer == renderer)
			{
				SAFE_DELETE(*itr);
				this->renderInfos.erase(itr);
				return;
			}
		}
	}
}